package com.zzy;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class SpeechSynthesizerDemo {

    public static String apiKey = "sk-7dd82cacca8f4f258a2e2be66a88beb4";
    // 模型
    private static String model = "cosyvoice-v2";
    // 音色
    private static String voice_chong_jie = "cosyvoice-v2-prefix-545aa6a0427a4ef5a8838ec6d4d88c08";

    private static String voice_ruan_mo = "cosyvoice-v2-prefix-0a923311ace841508271fd540cbecf75";

    private static String voice_bu_ke_si_yi = "cosyvoice-v2-prefix-6aa0ad6e5110462fa4ef44053fc6f67b";

    private static String voice_mo_ran = "cosyvoice-v2-prefix-b901e26359344597a077f75d1a02e2ac";

    private static String voice_dong_tian = "cosyvoice-v2-prefix-f9cc503f64894b36b2a9e567c4fa700b";


    public static void streamAudioDataToSpeaker() {
        // 请求参数
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        // 若没有将API Key配置到环境变量中，需将下面这行代码注释放开，并将your-api-key替换为自己的API Key
                        .apiKey(apiKey)
                        .model(model) // 模型
                        .voice(voice_dong_tian) // 音色
                        .build();

        // 同步模式：禁用回调（第二个参数为null）
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);

        String text =
         """
今天早上一上班，美女同事出了个谜语让我猜，“女上男下”，猜一个汽车的品牌，我想了半天也猜不出来。后来我也出了个谜语让她猜，“亲戚来了勿同房”，也猜一个汽车的品牌，她也猜不出来。劳资不禁感叹，真的是棋逢对手，将遇良才啊！
         """;



        // 阻塞直至音频返回
        ByteBuffer audio = synthesizer.call(text);
        // 将音频数据保存到本地文件“output.mp3”中
        File file = new File("D:\\test\\dongtian.mp3");
        System.out.println(
                "[Metric] requestId为："
                        + synthesizer.getLastRequestId()
                        + "首包延迟（毫秒）为："
                        + synthesizer.getFirstPackageDelay());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(audio.array());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        streamAudioDataToSpeaker();
        System.exit(0);
    }
}

